<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus'
// 声明百度地图相关的变量  
declare const BMAP_NORMAL_MAP: any;
declare const BMAP_EARTH_MAP: any;
declare const BMAP_SATELLITE_MAP: any;
// 用于初始化地图
let map: any = null
let degreeSet = reactive({
  longitude: '116.404',
  latitude: '39.915'
})
const { BMapGL } = window as any;
const initMap = () => {
  console.log(window, 'win')
  map = new BMapGL.Map("container");
  // 初始化地图,设置中心点坐标和地图级别
  map.enableScrollWheelZoom(true);
  let num = 5; // 默认级别
  switch (radio.value) {
    case 'BMAP_NORMAL_MAP':
      map.setMapType(BMAP_NORMAL_MAP);      // 设置地图类型为地球模式
      num = 11;
      break;
    case 'BMAP_EARTH_MAP':
      map.setMapType(BMAP_EARTH_MAP);
      num = 1;
    case 'BMAP_SATELLITE_MAP':
      map.setMapType(BMAP_SATELLITE_MAP);
      num = 5;
    default:
      break;
  }
  map.centerAndZoom(
    // 默认坐标注册
    new BMapGL.Point(degreeSet.longitude, degreeSet.latitude),
    num
  );
  var scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
  map.addControl(scaleCtrl);
  var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
  map.addControl(zoomCtrl);
  var LocationControl = new BMapGL.LocationControl();  // 添加定位控件，用于获取定位
  map.addControl(LocationControl);
  map.addEventListener('click', handleClick);
  function handleClick(e: any) {
    degreeSet.longitude = e.latlng.lng.toFixed(3);
    degreeSet.latitude = e.latlng.lat.toFixed(3);
  }

  // 右击菜单
  var menu = new BMapGL.ContextMenu();
  var txtMenuItem = [
    {
      text: '放大',
      callback: function () {
        map.zoomIn();
      }
    }, {
      text: '缩小',
      callback: function () {
        map.zoomOut();
      }
    }
  ];
  for (var i = 0; i < txtMenuItem.length; i++) {
    menu.addItem(new BMapGL.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, {
      width: 80,                             // 指定菜单项的宽度
      id: 'menu' + i                          // 指定菜单项dom的id
    }));
  }
  map.addContextMenu(menu); // 给地图添加右键菜单
}
// 加载地图
onMounted(() => {
  initMap();
})

// 点击搜索
const cityName = ref('');
const handleCityName = () => {
  // 判断用户是否输入
  if (!cityName.value.trim()) {
    // 提示用户
    ElMessage({
      message: '请输入城市名, 再进行搜索',
      type: 'warning',
    })
    return false;
  }
  const chineseRegex = /^[\u4e00-\u9fa5]+$/
  if(!chineseRegex.test(cityName.value)) {
    ElMessage({
      message: '输入内容只能是汉字, 不可包含字母, 数字和特殊字符',
      type: 'error'
    })
    return false
  }
  // 设置中心地图
  map.centerAndZoom(cityName.value, 11);
  // 创建地理编码实例
  getGeocoder(cityName.value)
}

// 更新经纬度
function getGeocoder(cityName: string) {
  let geoc = new BMapGL.Geocoder();
  geoc.getPoint(cityName, getPointTest, "中国");
  // 用于过滤获取经纬度
  function getPointTest(point: any) {
    if (point) {
      // 获取经纬度成功，point为经纬度对象
      // 更新经纬度
      degreeSet.longitude = point.lng.toFixed(3)
      degreeSet.latitude = point.lat.toFixed(3)
    } else {
      console.log("地址未找到"); // 地址未找到
    }
  }
}

// 通过ip地址进行定位
function getIpMap() {
  var myCity = new BMapGL.LocalCity();
  function myIpFun(result: any) {
    var cityName = result.name;
    map.centerAndZoom(cityName, 11);
    getGeocoder(cityName)
  }
  myCity.get(myIpFun);
}
getIpMap();


// 切换地图模式
const radio = ref('BMAP_NORMAL_MAP')
const tabRadioChange = (radioTab: string) => {
  // console.log(radioTab, 'tab')
  radio.value = radioTab
  // 重新加载地图
  initMap();
}


// 加载当前经纬度的全景图
const getPanorama = () => {
  var map = new BMapGL.Map('panorama');
	map.centerAndZoom(new BMapGL.Point(degreeSet.longitude, degreeSet.latitude), 12);
  map.addTileLayer(new BMapGL.PanoramaCoverageLayer());
  var panorama = new BMapGL.Panorama('panorama');
  panorama.setPov({ heading: -40, pitch: 6 });
  panorama.setPosition(new BMapGL.Point(degreeSet.longitude, degreeSet.latitude)); //根据经纬度坐标展示全景图		
}

const copyClick = async() => {
  // 判断有没有经纬度信息
  if(!degreeSet.longitude&&!degreeSet.latitude) {
    ElMessage({
      type: 'warning',
      message: '暂无经纬度信息, 不可复制'
    })
    return false;
  }
  await navigator.clipboard.writeText(`${degreeSet.longitude},${degreeSet.latitude}`);
  ElMessage({
    type: 'success',
    message: '复制成功!!!'
  })
}
</script>


<template>
  <div class="home">
    <div class="box">
      <h1 style="text-align: center;">百度地图简单使用</h1>
      <div class="search">
        <el-input style="width: 250px;" v-model="cityName"></el-input>
        <el-button type="primary" style="margin-left: 10px;" @click="handleCityName">搜索当地地图</el-button>
        <el-button type="primary" @click="getPanorama">加载当前经纬度的全景图</el-button>
      </div>
      <p style="color: red;">坐标展示: {{ degreeSet.longitude }} - {{ degreeSet.latitude }} <el-button type="primary" @click="copyClick" style="margin-left: 15px;">复制</el-button></p>
      <el-radio-group v-model="radio" @change="tabRadioChange">
        <el-radio value="BMAP_NORMAL_MAP">标准地图</el-radio>
        <el-radio value="BMAP_EARTH_MAP">地图模型</el-radio>
        <el-radio value="BMAP_SATELLITE_MAP">普通卫星地图</el-radio>
      </el-radio-group>
      <div id="container"></div>
      <!-- 全景图, 需要开通专门服务 -->
      <div id="panorama"></div>
    </div>
  </div>
</template>


<style scoped lang="scss">
#container {
  width: 100%;
  height: 650px;
}

@import './styles/app.scss'
</style>